<script setup lang="ts">
import type { PropType } from 'vue'
import { computed } from 'vue'
import { message } from 'ant-design-vue'
import type { PhaseType } from '@/types/micro-scene'
const props = defineProps({
  phases: {
    type: Array as PropType<PhaseType[]>,
    default: () => [],
  },
  lastActivePhaseId: {
    type: String,
    default: '1',
  },
  selectedPhaseId: {
    type: String,
    default: '1',
  },
})

const emit = defineEmits(['update:selectedPhase'])

const findPhaseIndex = (phaseId: string) => {
  // 如果phaseList为空，则返回-1
  if (props.phases.length === 0)
    return -1
  return props.phases.findIndex(Phase => Phase.phaseId === phaseId)
}

// 修改 phaseList 的初始化逻辑
const phaseList = computed(() => {
  // 如果传入了 Phases 且不为空，使用传入的 Phases
  if (props.phases && props.phases.length > 0)
    return props.phases

  // 同时发送报错信息
  message.error('阶段不能为空')
  // 直接返回默认阶段，不再设置 isActive
  return []
})

// 计算路径点
const pathPoints = computed(() => {
  const total = phaseList.value.length
  if (total === 0)
    return [] // 添加空数组检查

  const points: { x: number; y: number }[] = []

  // 增加波浪数量
  const numWaves = 4
  // 显著增加波浪幅度
  const amplitude = 45

  for (let i = 0; i < total; i++) {
    const progress = i / (total - 1)
    const x = 100 + progress * 800
    // 调整基准线位置和各波形的权重
    const y = 85
      + amplitude * Math.sin(progress * Math.PI * numWaves) * 0.6
      + amplitude * Math.sin(progress * Math.PI * (numWaves - 1)) * 0.35
      + amplitude * Math.sin(progress * Math.PI * (numWaves + 1)) * 0.25
      + amplitude * Math.sin(progress * Math.PI * (numWaves * 1.5)) * 0.15
    points.push({ x, y })
  }

  return points
})

// 生成SVG路径 - 添加安全检查
const svgPath = computed(() => {
  const points = pathPoints.value
  if (!points.length)
    return '' // 如果没有点，返回空路径

  let path = `M ${points[0].x} ${points[0].y}`

  for (let i = 1; i < points.length; i++) {
    const prevPoint = points[i - 1]
    const currentPoint = points[i]

    // 确保点存在
    if (!prevPoint || !currentPoint)
      continue

    const controlX1 = prevPoint.x + (currentPoint.x - prevPoint.x) * 0.3
    const controlX2 = prevPoint.x + (currentPoint.x - prevPoint.x) * 0.7
    const controlY1 = prevPoint.y + (currentPoint.y - prevPoint.y) * 0.15
    const controlY2 = currentPoint.y - (currentPoint.y - prevPoint.y) * 0.15

    path += ` C ${controlX1},${controlY1} ${controlX2},${controlY2} ${currentPoint.x},${currentPoint.y}`
  }

  return path
})

// 修改 pathTotalLength 计算，添加安全检查
const pathTotalLength = computed(() => {
  if (!svgPath.value)
    return 0 // 如果没有路径，返回0

  try {
    // 创建一个临时的 SVG path 元素来计算实际路径长度
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
    path.setAttribute('d', svgPath.value)
    const length = path.getTotalLength()
    return Math.ceil(length) // 向上取整确保完整覆盖
  }
  catch (error) {
    console.error('Error calculating path length:', error)
    return 0
  }
})

// 修改 activePathOffset 计算，添加安全检查
const activePathOffset = computed(() => {
  const totalLength = pathTotalLength.value
  if (!totalLength || !props.lastActivePhaseId || !phaseList.value.length)
    return totalLength

  let currentIndex = findPhaseIndex(props.lastActivePhaseId)
  // 如果当前阶段不存在，则为开始
  if (currentIndex === -1)
    currentIndex = 0
  const progress = currentIndex / (phaseList.value.length - 1)
  return totalLength * (1 - progress)
})

// 处理阶段点击
const handlePhaseClick = (phaseId: string) => {
  emit('update:selectedPhase', phaseId)
}

// 添加计算属性判断是否为当前选中的旗子
const isCurrentPhase = (phaseId: string) => {
  return phaseId === props.selectedPhaseId
}

// 添加文本换行处理函数
const formatPhaseName = (name: string) => {
  // 每6个字符换行
  const maxLength = 7
  if (name.length <= maxLength)
    return [name]

  const lines: string[] = []
  for (let i = 0; i < name.length; i += maxLength)
    lines.push(name.slice(i, i + maxLength))

  return lines
}

// 修改计算文本初始 y 位置的函数
const getTextPosition = (name: string) => {
  const lines = formatPhaseName(name)
  const lineHeight = 16 // 每行文字高度（像素）
  const baseOffset = -40 // 基础偏移量
  const totalHeight = (lines.length - 1) * lineHeight // 总高度（不包括第一行）

  return {
    baseY: baseOffset - totalHeight, // 起始位置上移
    lineHeight,
  }
}

// 添加计算属性判断是否为活跃状态
const isActivePhase = (phaseId: string) => {
  return findPhaseIndex(phaseId) <= findPhaseIndex(props.lastActivePhaseId)
}
</script>

<template>
  <div class="relative w-full min-h-[15rem] overflow-hidden">
    <!-- SVG 容器 -->
    <svg
      class="w-full h-full"
      viewBox="0 -30 1000 200"
      preserveAspectRatio="xMidYMid meet"
    >
      <!-- 只在有路径时渲染 -->
      <template v-if="svgPath">
        <!-- 路径背景 -->
        <path
          :d="svgPath"
          class="stroke-gray-200"
          fill="none"
          stroke-width="3"
        />
        <!-- 活跃路径 -->
        <path
          :d="svgPath"
          class="stroke-blue-500"
          fill="none"
          stroke-width="3"
          :stroke-dasharray="pathTotalLength"
          :stroke-dashoffset="activePathOffset"
          stroke-linecap="round"
        />
      </template>

      <!-- 只在有点数据时渲染旗子 -->
      <template v-if="pathPoints.length">
        <!-- 阶段标记点和旗子 -->
        <g
          v-for="(phase, index) in phaseList"
          :key="phase.phaseId"
          :transform="`translate(${pathPoints[index].x}, ${pathPoints[index].y})`"
          class="cursor-pointer"
          @click="handlePhaseClick(phase.phaseId)"
        >
          <!-- 旗子图标 -->
          <g :class="{ 'text-blue-500': isActivePhase(phase.phaseId), 'text-gray-400': !isActivePhase(phase.phaseId) }">
            <!-- 旗子头部 -->
            <path
              d="M0,-30 L0,-15 L12,-22.5 L0,-30"
              :fill="isActivePhase(phase.phaseId) ? '#3B82F6' : '#9CA3AF'"
            />
            <!-- 旗子杆 -->
            <line
              x1="0"
              y1="-30"
              x2="0"
              y2="0"
              :stroke="isActivePhase(phase.phaseId) ? '#3B82F6' : '#9CA3AF'"
              stroke-width="2"
            />
            <!-- 添加选中标识小三角 -->
            <path
              v-if="isCurrentPhase(phase.phaseId)"
              d="M-6,8 L6,8 L0,14 Z"
              fill="#3B82F6"
              class="triangle-indicator"
            />
          </g>

          <!-- 阶段名称 -->
          <text
            text-anchor="middle"
            class="text-sm font-medium"
            :class="{
              'fill-blue-500': isActivePhase(phase.phaseId),
              'fill-gray-500': !isActivePhase(phase.phaseId),
              'font-bold': isCurrentPhase(phase.phaseId),
            }"
          >
            <template v-if="phase.phaseTitle">
              <tspan
                v-for="(line, index) in formatPhaseName(phase.phaseTitle)"
                :key="index"
                x="0"
                :y="getTextPosition(phase.phaseTitle).baseY + index * getTextPosition(phase.phaseTitle).lineHeight"
              >
                {{ line }}
              </tspan>
            </template>
          </text>
        </g>
      </template>
    </svg>
  </div>
</template>

<style scoped lang="scss">
path {
  transition: stroke-dashoffset 0.8s ease;
}

.triangle-indicator {
  transition: opacity 0.3s ease;
}

text {
  user-select: none;
}
</style>

<!-- 设计说明：
  # 绘制活跃路径
  pathPoints 计算路径上的节点；svgPath 计算路径的贝塞尔曲线
  活跃路径的工作原理：
  - 双路径叠加：使用两个完全相同的路径重叠,底部是完整的灰色路径,顶部是蓝色路径
  - stroke-dasharray: 设置为实际路径长度，确保准确的路径覆盖
  - 活跃路径偏移量计算：
    1. 通过 SVG path 的 getTotalLength() 方法获取实际路径长度
    2. 根据当前选中的阶段计算进度比例
    3. 使用实际长度和进度比例计算偏移量，确保与旗子位置精确对齐
-->
